import axios from 'axios'

// 根据环境决定 baseURL：
// - 生产：使用公开域名 https://api.cumrbull.com.sg
// - 开发：保持相对路径，由 Vite 代理到本地后端
const isProd = typeof window !== 'undefined' && window.location && window.location.hostname.endsWith('cumrbull.com.sg')
const defaultBaseURL = isProd ? 'https://api.cumrbull.com.sg' : ''

const api = axios.create({
  baseURL: defaultBaseURL,
  withCredentials: true,
  timeout: 15000
})

// 安全的JSON解析函数
const safeJsonParse = (text, requestId = 'unknown') => {
  try {
    return JSON.parse(text);
  } catch (error) {
    console.error(`[${requestId}] JSON解析失败:`, error.message);
    return {
      success: false,
      phase: 'system',
      status: 'failed',
      summary: { inserted: 0, updated: 0, skipped: 0, error_count: 0 },
      errors: [],
      warnings: [],
      system_error: `Invalid response format: ${text.slice(0, 200)}`,
      requestId: requestId
    };
  }
};

// 安全的fetch函数
const safeFetch = async (url, options = {}) => {
  try {
    const response = await fetch(url, {
      ...options,
      headers: {
        'Content-Type': 'application/json',
        ...options.headers
      }
    });
    
    const requestId = response.headers.get('X-Request-Id') || 'no-id';
    const contentType = response.headers.get('Content-Type') || '';
    
    // 获取响应文本
    const text = await response.text();
    
    if (!response.ok) {
      // HTTP错误状态
      if (contentType.includes('application/json') && text) {
        const errorData = safeJsonParse(text, requestId);
        throw new Error(`[${requestId}] Server error: ${response.status} - ${errorData.system_error || errorData.message || 'Unknown error'}`);
      } else {
        throw new Error(`[${requestId}] Server error: ${response.status} - ${text.slice(0, 200)}`);
      }
    }
    
    // 检查Content-Type
    if (!contentType.includes('application/json')) {
      throw new Error(`[${requestId}] Invalid response format: ${text.slice(0, 200)}`);
    }
    
    // 解析JSON
    const data = safeJsonParse(text, requestId);
    data.requestId = requestId;
    return data;
  } catch (error) {
    console.error('API请求失败:', error);
    throw error;
  }
};

api.interceptors.request.use(
  (config) => {
    const token = (typeof window !== 'undefined' && window.localStorage)
      ? (localStorage.getItem('admin_token') || localStorage.getItem('token'))
      : null
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }

    // 为GET请求添加防缓存参数与请求头，避免304
    if ((config.method || 'get').toLowerCase() === 'get') {
      const ts = Date.now()
      config.params = { ...(config.params || {}), _t: ts }
      config.headers['Cache-Control'] = 'no-cache'
      config.headers['Pragma'] = 'no-cache'
      config.headers['If-Modified-Since'] = '0'
    }
    console.log('API请求:', config.method, config.url, config.data || config.params)
    return config
  },
  (error) => Promise.reject(error)
)

api.interceptors.response.use(
  (response) => {
    console.log('API响应成功:', response.config.url, response.status, response.data)
    return response
  },
  (error) => {
    console.error('API响应错误:', error.config?.url, error.response?.status, error.message, error.response?.data)
    if (error.response && error.response.status === 401) {
      try {
        localStorage.removeItem('admin_token')
        localStorage.removeItem('token')
      } catch {
        // 静默处理本地存储清除失败
      }
      // 可在此触发跳转登录
    }
    return Promise.reject(error)
  }
)

// 认证相关 API
export const authAPI = {
  login: (credentials) => api.post('/api/auth/login', credentials),
  logout: () => api.post('/api/auth/logout'),
  getCurrentUser: () => api.get('/api/auth/me'),
  checkAdminAccess: () => api.get('/admin/system/info')
}

// 仪表板相关 API
export const dashboardAPI = {
  getStats: (timeRange = '7d') => api.get(`/api/admin/dashboard/stats?timeRange=${timeRange}`),
  getRealtimeData: () => api.get('/api/admin/dashboard/realtime'),
  getRecentOrders: () => api.get('/api/admin/dashboard/recent-orders'),
  getRevenueTrends: () => api.get('/api/admin/dashboard/revenue-trends'),
  getCategoryDistribution: () => api.get('/api/admin/dashboard/category-distribution')
}

// 用户管理 API
export const userAPI = {
  getUsers: (params) => api.get('/api/admin/users', { params }),
  getUserById: (id) => api.get(`/api/admin/users/${id}`),
  updateUserStatus: (id, data) => api.put(`/api/admin/users/${id}/status`, data),
  deleteUser: (id) => api.delete(`/api/admin/users/${id}`),
  getUserStatistics: () => api.get('/api/admin/users/statistics')
}

// 菜单管理 API
export const menuAPI = {
  getCategories: (params) => api.get('/api/admin/menu/categories', { params }),
  createCategory: (data) => api.post('/api/admin/menu/categories', data),
  updateCategory: (id, data) => api.put(`/api/admin/menu/categories/${id}`, data),
  deleteCategory: (id) => api.delete(`/api/admin/menu/categories/${id}`),
  getMenuItems: (params) => {
    // 添加当前语言参数
    const lang = localStorage.getItem('admin_language') || 'zh';
    return api.get('/api/menu/public/items', { params: { ...params, lang } });
  },
  createMenuItem: (data) => api.post('/api/admin/menu/items', data),
  updateMenuItem: (id, data) => api.put(`/api/admin/menu/items/${id}`, data),
  deleteMenuItem: (id) => api.delete(`/api/admin/menu/items/${id}`),

  updateAvailability: (id, data) => api.put(`/api/admin/menu/items/${id}/availability`, data),
  uploadItemImage: async (id, file) => {
    try {
      const form = new FormData()
      form.append('image', file)
      const token = localStorage.getItem('admin_token');
      const data = await safeFetch(`/api/admin/menu/items/${id}/image`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`
        },
        body: form
      });
      return { data };
    } catch (error) {
      console.error('上传菜品图片失败:', error);
      throw error;
    }
  },
  uploadMenuImages: async (files) => {
    try {
      const form = new FormData()
      files.forEach((f) => form.append('images', f))
      const token = localStorage.getItem('admin_token');
      const data = await safeFetch('/api/admin/menu/images/batch', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`
        },
        body: form
      });
      return { data };
    } catch (error) {
      console.error('批量上传菜单图片失败:', error);
      throw error;
    }
  },
  // Excel导入导出功能 - V2三表结构（Dishes/Variants/Options）
  downloadTemplate: () => {
    const isProd = typeof window !== 'undefined' && window.location && window.location.hostname.endsWith('cumrbull.com.sg')
    const baseURL = isProd ? 'https://api.cumrbull.com.sg' : 'http://localhost:3001'
    return axios.get(`${baseURL}/api/admin/menu-import/v2/template/menu.xlsx`, {
      responseType: 'blob',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('admin_token')}`
      }
    })
  },
  exportMenu: (params = {}) => {
    const isProd = typeof window !== 'undefined' && window.location && window.location.hostname.endsWith('cumrbull.com.sg')
    const baseURL = isProd ? 'https://api.cumrbull.com.sg' : 'http://localhost:3001'
    return axios.get(`${baseURL}/api/admin/menu-import/v2/export/menu`, {
      params,
      responseType: 'blob',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('admin_token')}`
      }
    })
  },
  validateMenu: (file) => {
    const form = new FormData()
    form.append('file', file)
    const token = localStorage.getItem('admin_token')
    if (!token) {
      throw new Error('未找到认证token，请先登录')
    }
    console.log('发送V2验证请求，token:', token.substring(0, 50) + '...')
    return api.post('/api/admin/menu-import/v2/validate', form, {
      headers: { 
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${token}`
      },
      timeout: 60000  // 增加超时时间到60秒
    })
  },
  commitImport: (jobId) => {
    const token = localStorage.getItem('admin_token')
    if (!token) {
      throw new Error('未找到认证token，请先登录')
    }
    console.log('发送V2提交请求，jobId:', jobId, 'token:', token.substring(0, 50) + '...')
    return api.post(`/api/admin/menu-import/v2/commit?job_id=${jobId}`, {}, {
      headers: {
        'Authorization': `Bearer ${token}`
      },
      timeout: 60000  // 增加超时时间到60秒
    })
  },
  getJobStatus: async (jobId) => {
    try {
      // 使用安全的fetch函数替代axios
      const token = localStorage.getItem('admin_token');
      const isProd = typeof window !== 'undefined' && window.location && window.location.hostname.endsWith('cumrbull.com.sg')
      const baseURL = isProd ? 'https://api.cumrbull.com.sg' : 'http://localhost:3001'
      const data = await safeFetch(`${baseURL}/api/admin/menu-import/v2/jobs/${jobId}`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      return { data };
    } catch (error) {
      console.error('获取任务状态失败:', error);
      throw error;
    }
  },
  downloadErrors: (jobId) => {
    const token = localStorage.getItem('admin_token')
    if (!token) {
      throw new Error('未找到认证token，请先登录')
    }
    const isProd = typeof window !== 'undefined' && window.location && window.location.hostname.endsWith('cumrbull.com.sg')
    const baseURL = isProd ? 'https://api.cumrbull.com.sg' : 'http://localhost:3001'
    return axios.get(`${baseURL}/api/admin/menu-import/v2/jobs/${jobId}/validate-report`, { 
      responseType: 'blob',
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
  }
}

// 订单管理 API
export const orderAPI = {
  // 调整为通用订单路由（由路由自身进行管理员鉴权），避免某些环境下 /api/admin 未挂载导致的404
  getOrders: (params) => api.get('/api/orders/admin/all', { params }),
  getOrderById: (id) => api.get(`/api/orders/${id}`),
  updateOrderStatus: (id, data) => api.put(`/api/orders/${id}/status`, data),
  getOrderStatistics: (params) => api.get('/api/orders/stats', { params }),
  getPopularItems: (params) => api.get('/api/orders/popular-items', { params }),
  getCategorySales: (params) => api.get('/api/orders/categories', { params }),
  getOrderTypeDistribution: (params) => api.get('/api/orders/type-distribution', { params }),
  getPaymentMethodDistribution: (params) => api.get('/api/orders/payment-distribution', { params }),
  getTopCustomers: (params) => api.get('/api/orders/top-customers', { params }),
  // 新增：趋势接口
  getOrderTypeTrend: (params) => api.get('/api/orders/trends', { params }),
  getPaymentMethodTrend: (params) => api.get('/api/orders/payment-trend', { params })
}

// 优惠券管理 API（保留原实现，供 Coupons 页面使用）
export const couponAPI = {
  getCoupons: (params) => api.get('/api/admin/coupons', { params }),
  createCoupon: (data) => api.post('/api/admin/coupons', data),
  updateCoupon: (id, data) => api.put(`/api/admin/coupons/${id}`, data),
  deleteCoupon: (id) => api.delete(`/api/admin/coupons/${id}`),
  batchDistribute: (data) => api.post('/api/admin/coupons/batch-distribute', data),
  getCouponStatistics: () => api.get('/api/admin/coupons/statistics')
}

// 系统管理 API
export const systemAPI = {
  getSystemInfo: () => api.get('/api/admin/system/info'),
  getSystemLogs: (params) => api.get('/api/admin/system/logs', { params }),
  clearCache: () => api.post('/api/admin/system/clear-cache')
}

// 报表管理 API
export const reportAPI = {
  // 获取报表列表
  getReportList: () => api.get('/api/reports'),
  
  // 获取报表配置
  getReportConfig: (reportKey) => api.get(`/api/reports/config/${reportKey}`),
  
  // 财务类报表
  getCashDeclarationReport: (filters) => api.post('/api/reports/financial/cash-declaration', filters),
  getDailyCollectionReport: (filters) => api.post('/api/reports/financial/daily-collection', filters),
  getPaymentReport: (filters) => api.post('/api/reports/financial/payment-report', filters),
  getProfitAnalysisReport: (filters) => api.post('/api/reports/financial/profit-analysis', filters),
  
  // 销售类报表
  getDailySalesSummaryReport: (filters) => api.post('/api/reports/sales/daily-summary', filters),
  getHourlyAnalysisReport: (filters) => api.post('/api/reports/sales/hourly-analysis', filters),
  getHourlyOverviewReport: (filters) => api.post('/api/reports/sales/hourly-overview', filters),
  getSalesAndCountReport: (filters) => api.post('/api/reports/sales/sales-and-count', filters),
  
  // 商品类报表
  getProductSalesReport: (filters) => api.post('/api/reports/product/sales-report', filters),
  getProductAnalysisReport: (filters) => api.post('/api/reports/product/analysis-report', filters),
  getProductReturnReport: (filters) => api.post('/api/reports/product/return-report', filters),
  getCondimentsReport: (filters) => api.post('/api/reports/product/condiments-report', filters),
  getDiscountReport: (filters) => api.post('/api/reports/product/discount-report', filters),
  
  // 顾客与服务类报表
  getRatingReport: (filters) => api.post('/api/reports/customer/rating-report', filters),
  getReceiptJournalReport: (filters) => api.post('/api/reports/customer/receipt-journal', filters),
  getHourlyItemReport: (filters) => api.post('/api/reports/customer/hourly-item-report', filters),
  getPaymentProductReport: (filters) => api.post('/api/reports/customer/payment-product-report', filters),
  
  // 导出功能
  exportReport: (reportKey, format, filters) => api.post(`/api/reports/export/${reportKey}`, { format, filters }),
  getExportStatus: (exportId) => api.get(`/api/reports/export/status/${exportId}`),
  downloadExportFile: (exportId) => api.get(`/api/reports/export/download/${exportId}`, { responseType: 'blob' }),
  
  // 权限管理
  getReportPermissions: () => api.get('/api/reports/permissions'),
  updateReportPermissions: (role, reportKey, permissions) => api.put('/api/reports/permissions', { role, reportKey, permissions }),
  
  // 订阅管理
  getReportSubscriptions: () => api.get('/api/reports/subscriptions'),
  createReportSubscription: (data) => api.post('/api/reports/subscriptions', data),
  updateReportSubscription: (subscriptionId, data) => api.put(`/api/reports/subscriptions/${subscriptionId}`, data),
  deleteReportSubscription: (subscriptionId) => api.delete(`/api/reports/subscriptions/${subscriptionId}`)
}

// 邀请管理 API
export const inviteAPI = {
  getInviteRecords: (params) => api.get('/api/invites/records', { params }),
  getInviteStats: () => api.get('/api/invites/stats'),
  generateInviteCode: () => api.post('/api/invites/generate'),
  issueCoupon: (id, data) => api.post(`/api/invites/issue-coupon/${id}`, data),
  getMyInvites: (params) => api.get('/api/invites/my-invites', { params }),
  getMyStats: () => api.get('/api/invites/my-stats')
}

export default api


// 添加postJSON请求包装器，避免静默失败
export async function postJSON(url, body, opts={}) {
  const res = await fetch(url, { 
    method: 'POST', 
    headers: { 
      'Content-Type': 'application/json', 
      ...(opts.headers || {}) 
    }, 
    body: JSON.stringify(body) 
  });
  const text = await res.text().catch(() => '');
  let data;
  try { 
    data = text ? JSON.parse(text) : {}; 
  } catch { 
    data = { raw: text }; 
  }
  if (!res.ok) throw new Error(data?.message || `HTTP ${res.status} ${res.statusText}`);
  return { data, status: res.status };
}